import os
import shutil
from pathlib import Path


def clear_huggingface_cache():
    """清理Hugging Face缓存"""

    # 获取缓存目录
    cache_dirs = [
        Path.home() / ".cache" / "huggingface",
        Path.home() / ".cache" / "transformers",
        Path(os.environ.get('HF_HOME', Path.home() / ".cache" / "huggingface")),
        Path(os.environ.get('TRANSFORMERS_CACHE', Path.home() / ".cache" / "transformers"))
    ]

    print("=== 清理Hugging Face缓存 ===")

    for cache_dir in cache_dirs:
        if cache_dir.exists():
            try:
                print(f"正在清理: {cache_dir}")
                # 只删除SeamlessM4T相关的缓存
                for item in cache_dir.glob("*seamless*"):
                    if item.is_dir():
                        shutil.rmtree(item)
                        print(f"已删除: {item}")
                    elif item.is_file():
                        item.unlink()
                        print(f"已删除: {item}")

                # 也删除models目录下的seamless相关文件
                models_dir = cache_dir / "models"
                if models_dir.exists():
                    for item in models_dir.glob("*seamless*"):
                        if item.is_dir():
                            shutil.rmtree(item)
                            print(f"已删除: {item}")

            except Exception as e:
                print(f"清理 {cache_dir} 时出错: {e}")
        else:
            print(f"缓存目录不存在: {cache_dir}")

    print("缓存清理完成！")


def download_model_manually(model_name):
    """手动下载模型"""
    print(f"\n=== 手动下载模型: {model_name} ===")

    try:
        from transformers import AutoConfig, AutoProcessor
        from huggingface_hub import snapshot_download

        print("正在下载模型配置...")
        config = AutoConfig.from_pretrained(model_name, force_download=True)
        print("配置下载成功")

        print("正在下载处理器...")
        processor = AutoProcessor.from_pretrained(model_name, force_download=True)
        print("处理器下载成功")

        print("正在下载完整模型...")
        snapshot_download(repo_id=model_name, force_download=True)
        print("模型下载完成")

        return True

    except Exception as e:
        print(f"手动下载失败: {e}")
        return False


if __name__ == "__main__":
    # 清理缓存
    clear_huggingface_cache()

    # 尝试重新下载模型
    # models_to_try = [
    #     "facebook/seamless-m4t-v2-large"
    # ]

    # for model in models_to_try:
    #     print(f"\n尝试下载 {model}...")
    #     if download_model_manually(model):
    #         print(f"✓ {model} 下载成功")
    #         break
    #     else:
    #         print(f"✗ {model} 下载失败")

    print("\n请重启Python环境后再次尝试运行程序")
